package proj.unions.cppmanager;

import org.cocos2dx.lib.Cocos2dxGLSurfaceView;
import org.cocos2dx.lib.Cocos2dxHelper;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import proj.unions.game.MainActivity;
import proj.unions.game.ThirdLogin;
import proj.unions.game.ThirdPay;
import proj.unions.general.L;
import proj.unions.general.ProperTiesCondefine;
import proj.unions.general.PropertiesData;
import proj.unions.general.SuperTools;
import proj.unions.resource.RMConstDefine;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;

public class CPPManager {
	
	final public String Third_Install_Apk_Zip_Dir_C2J 				= "Third_Install_Apk_Zip_Dir_C2J";
	final public String Third_Install_Apk_Zip_Filter_C2J 			= "Third_Install_Apk_Zip_Filter_C2J";
	
	final public String Third_Test = "Third_Test";
	final public String Third_ThirdPlatformManager_Has_Created_C2J	= "Third_ThirdPlatformManager_Has_Created_C2J";
	final public String Third_Log_Debug_C2J							= "Third_Log_Debug_C2J";
	final public String Third_RoleInfo_Has_Finished_C2J				= "Third_RoleInfo_Has_Finished_C2J";
	final public String Third_Login_UserName_C2J					= "Third_Login_UserName_C2J";
	final public String Third_Login_UserPassword_C2J				= "Third_Login_UserPassword_C2J";
	final public String Third_Login_IP_C2J							= "Third_Login_IP_C2J";
	final public String Third_Login_Port_C2J						= "Third_Login_Port_C2J";
	final public String Third_Login_UniondId_C2J					= "Third_Login_UniondId_C2J";
	final public String Third_GameRes_Path_C2J						= "Third_GameRes_Path_C2J";
	final public String Third_Show_Login_C2J						= "Third_Show_Login_C2J";
	final public String Third_Show_Payment_C2J						= "Third_Show_Payment_C2J";
	final public String Third_Mobile_Model_C2J						= "Third_Mobile_Model_C2J";
	final public String Third_Local_Service_C2J						= "Third_Local_Service_C2J";

	final public String Third_CPPPlarformManager_Has_Created_J2C	= "Third_CPPPlarformManager_Has_Created_J2C";
	final public String Third_Enter_Second_J2C						= "Third_Enter_Second_J2C";
	final public String Third_Exit_Game_J2C 						= "Third_Exit_Game_J2C";
	
	//Sound SDK
	final public String Third_Sound_StartRecord = "Third_Sound_StartRecord";
	final public String Third_Sound_StopRecord = "Third_Sound_StopRecord";
	final public String Third_Sound_PlayRecord = "Third_Sound_PlayRecord";
	final public String Third_Sound_URL_TEXT = "Third_Sound_URL_TEXT";
	final public String Third_RoleInfo_Sound_C2J = "Third_RoleInfo_Sound_C2J";
	final public String Third_Set_BackSound_C2J = "Third_Set_BackSound_C2J";
	
	//充值 SDK
	final public String Third_Recharge_C2J = "Third_Recharge_C2J";
	final public String Third_Recharge_J2C = "Third_Recharge_J2C";
	
	//设置登录服地址
	final public String Third_SetLoginServiceAddress_J2C = "Third_SetLoginServiceAddress_J2C";
	//存储手机信息
	final public String Third_SavePhoneInfo_J2C = "Third_SavePhoneInfo_J2C";
	//手机网络状态
	final public String Third_GetPhoneNetworkType_C2J = "Third_GetPhoneNetworkType_C2J";
	final public String Third_GetPhoneNetworkIsConn_C2J = "Third_GetPhoneNetworkIsConn_C2J";
	//渠道id
	final public String Third_UnionId_J2C = "Third_UnionId_J2C";
	//通知android弹ad
	final public String Third_PopAd_C2J = "Third_PopAd_C2J";
	//发送返回键事件
	final public String Third_NoticeBackBtnEvent_C2J = "Third_NoticeBackBtnEvent_C2J";
	//获取apk账户名
	final public String Third_APK_Account_C2J = "Third_APK_Account_C2J";
	//获取apk密码
	final public String Third_APK_Password_C2J = "Third_APK_Password_C2J";
	//通知第三方(and游戏)重新登录
	final public String Third_NoticeReLogin_C2J = "Third_NoticeReLogin_C2J";
	final public String Third_NoticeReLogin_J2C = "Third_NoticeReLogin_J2C";
	final public String Third_NoticeLogin_J2C = "Third_NoticeLogin_J2C";
	//显示/隐藏登陆按钮
	final public String Third_OperateLoginBtn_J2C = "Third_OperateLoginBtn_J2C";
	//发送游戏状态
	final public String Third_NoticeGameStatus_C2J = "Third_NoticeGameStatus_C2J";
	//发送角色状态
	final public String Third_PlayerStatus_C2J = "Third_PlayerStatus_C2J";
	//使用android http
	final public String Third_UseAndroidHttp_C2J = "Third_UseAndroidHttp_C2J";
	//优化android输入框(增加机型白名单)
	final public String Third_InputWhiteList_C2J = "Third_InputWhiteList_C2J";
	
	private static CPPManager mTPM = null;
	private String playerUuid = "";
	private String playerName = "";

	private boolean isInitCPPManager = false;
	private static int loginCount = 0;
	
	public static CPPManager getInstance() {
		if (mTPM == null)
			mTPM = new CPPManager();
		return mTPM;
	}

	// ================================异步========================================
	//发送
	public void send(String eventType, String eventParam, String eventJson)
	{
//		if (!isInitCPPManager)
//			return;
		Cocos2dxHelper.sendMsgToCPlusPlus(eventType, eventParam, eventJson);
	}
	//接收
	public void recv(String eventType, String eventParam, JSONObject eventJson) 
	{	
		if (eventType.equals(Third_ThirdPlatformManager_Has_Created_C2J))
		{
			isInitCPPManager = true;
			Cocos2dxHelper.sendMsgToCPlusPlus(
					Third_CPPPlarformManager_Has_Created_J2C, "2",
					new JSONObject().toString());
			//发送ip地址
			sendLoginAddress();
			//发送手机信息
			sendPhoneInfo();

		}
		else if (eventType.equals(Third_RoleInfo_Has_Finished_C2J)) 
		{
			// 拿到loginId和serverId
			L.d("role data:" + eventParam);
		
		}
		else if (eventType.equals(Third_Log_Debug_C2J)) 
		{
			L.d("debug:" + eventParam);
		}
		else if (eventType.equals(Third_Sound_StartRecord)) 
		{
			
		}
		else if (eventType.equals(Third_Sound_StopRecord))
		{
			
		}
		else if (eventType.equals(Third_Sound_PlayRecord)) 
		{
			
			
		}
		else if (eventType.equals(Third_RoleInfo_Sound_C2J))
		{
			L.d("debug:" + eventParam);
			//此处初始化sdk
			try { 
				JSONObject tp = new JSONObject(eventParam);
				playerUuid = tp.getString("uuid");
				playerName = tp.getString("name");
				
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		else if(eventType.equals(Third_Recharge_C2J))
		{
			recharge(eventParam, eventJson);
		}
		else if(eventType.equals(Third_PopAd_C2J))
		{

		}
		else if(eventType.equals(Third_NoticeBackBtnEvent_C2J))
		{
			//返回键通知事件
			MainActivity.exitGame();
		}
		else if(eventType.equals(Third_NoticeReLogin_C2J))
		{
			//通知第三方重登录
			L.d("===from login eventParam:" + eventParam);
			if(eventParam.equals("OpenLoginUI"))
			{
				if(loginCount <= 0)
					ThirdLogin.fromOpenLoginUI(true);	//第一次进是提交参数
				else
					ThirdLogin.fromOpenLoginUI(false);	//以后进是呼出第三方登录界面
				loginCount++;
			}
			else if(eventParam.equals("CloseLoginUI"))
			{
				ThirdLogin.fromCloseLoginUI();
			}
			else if(eventParam.equals("ClickLoginBtn"))
			{
				ThirdLogin.fromClickLoginBtn();
			}
			else if(eventParam.equals("LoginSuccess"))
			{
				ThirdLogin.fromLoginStatus(true);
			}
			else if(eventParam.equals("LoginFailed"))
			{
				ThirdLogin.fromLoginStatus(false);
			}
			
		}
		else if(eventType.equals(Third_NoticeGameStatus_C2J))
		{
			L.d("==================GameStatus:" + eventParam);
			try { 
				int serverId = eventJson.getInt("serverId");
				String serverName = eventJson.getString("serverName");
				String loginId = eventJson.getString("loginId");
				String uuid = eventJson.getString("uuid");
				String roleName = eventJson.getString("roleName");
				int roleLv = eventJson.getInt("roleLv");
				int roleVipLv = eventJson.getInt("roleVipLv");
				
				//"login" "selectServer" "entryGame" "showLoadResBg"
				if(eventParam.equals("entryGame"))//eventParam表示状态
				{
					
				}
				else if(eventParam.equals("showLoadResBg"))
				{
					MainActivity.closeOverUi();
				}
				
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		else if(eventType.equals(Third_PlayerStatus_C2J))
		{
			L.d("==================GPlayerStatus:" + eventParam);
			try { 
				int serverId = eventJson.getInt("serverId");
				String serverName = eventJson.getString("serverName");
				String loginId = eventJson.getString("loginId");
				String uuid = eventJson.getString("uuid");
				String roleName = eventJson.getString("roleName");
				int roleLv = eventJson.getInt("roleLv");
				int roleVipLv = eventJson.getInt("roleVipLv");
				
				//"upgradeRoleLv" , "createName"
				if(eventParam.equals("upgradeRoleLv"))//eventParam表示状态
				{
					
				}
				else if(eventParam.equals("createName"))//eventParam表示状态
				{
					
				}
				
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		else if(eventType.equals(Third_InputWhiteList_C2J))
		{
			//eventParam == "All" 等于全部使用
			Cocos2dxGLSurfaceView.isAllUse = false;
			Cocos2dxGLSurfaceView.mLocalWhiteList.clear();
			
			if(eventParam.equals("All"))
				Cocos2dxGLSurfaceView.isAllUse = true;
			else
			{
				String argList[] = eventParam.split("#");
				for(int i = 0; i < argList.length; i++)
					Cocos2dxGLSurfaceView.mLocalWhiteList.add(argList[i]);
			}
			//设置时间
			try {
				if(eventJson.has("hideGameUITime"))
					Cocos2dxGLSurfaceView.hideGameUITime = eventJson.getInt("hideGameUITime");
				if(eventJson.has("showGameUITime"))
					Cocos2dxGLSurfaceView.showGameUITime = eventJson.getInt("showGameUITime");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	// =======================================同步处理==========================================
	//发送
	public String getResultFromCPP(String eventType, String eventParam,String eventJson) 
	{
//		if (!isInitCPPManager)
//			return "Has not been initialized!";
		return Cocos2dxHelper.getResultFromCPP(eventType, eventParam, eventJson);
	}
	//接收
	public String returnResultToCPP(String eventType, String eventParam,String eventJson) 
	{
		String data = "";
		if (eventType.equals(Third_Test)) 
		{
			
		}
		else if(eventType.equals(Third_Login_UserName_C2J))//用户名
		{
			SharedPreferences sharedata = SuperTools.getInstance().getCurActivity().getSharedPreferences("login_data", 0);
			data = sharedata.getString("name", "");
		}
		else if(eventType.equals(Third_Login_UserPassword_C2J))//密码
		{
			SharedPreferences sharedata = SuperTools.getInstance().getCurActivity().getSharedPreferences("login_data", 0);
			data = sharedata.getString("pw", "");
		}
		else if(eventType.equals(Third_Login_UniondId_C2J))//密码
		{
//			data = ThirdConstDefine.UnionId_Release;
		}
		else if ( eventType.equals(Third_GameRes_Path_C2J) )
		{
			//返回apk资源路径
			String apkPath = SuperTools.getInstance().getAPKPath();
			return apkPath;
		}
		else if( eventType.equals(Third_GetPhoneNetworkType_C2J))
		{
			int type = SuperTools.getInstance().getPhoneNetworkType();
			return String.valueOf(type);
		}
		else if( eventType.equals(Third_GetPhoneNetworkIsConn_C2J))
		{
			boolean flag = SuperTools.getInstance().getPhoneIsConnected();
			return String.valueOf(flag);
		}
		if (eventType.equals(Third_Install_Apk_Zip_Dir_C2J)) 
		{
			data = SuperTools.getInstance().getCurActivity().getApplicationInfo().sourceDir;
		}
		else if (eventType.equals(Third_Install_Apk_Zip_Filter_C2J)) 
		{
			data = "pkm";
		}
		else if (eventType.equals(Third_APK_Account_C2J)) 
		{
			data = MainActivity.gAccount;
			L.d("==========_APK_Account_C2J");
		}
		else if (eventType.equals(Third_APK_Password_C2J)) 
		{
			data = MainActivity.gPassword;
		}
		return data;
	}
	
//-------------------------------------交互业务----------------------------------------------
	
	//Sound SDK
	public void sendSoundInfoToCpp(String tag,String url,String re_text)
	{
		try {
			JSONObject tp = new JSONObject();
			tp.put("RoomExt", tag);
			tp.put("voiceUrl", url);
			tp.put("readText", re_text);
			send(Third_Sound_URL_TEXT, url, tp.toString());
		} catch (Exception e) {
			// TODO: handle exception
			Log.d(tag,"send sendSoundInfoToCpp failed");
		}
	}
	
	public String getUuid()
	{
		return playerUuid;
	}
	
	public String getName()
	{
		return playerName;
	}
	
	//通知游戏清除数据回到登陆界面重登陆游戏
	public void noticeGameReLogin()
	{
		send(Third_NoticeReLogin_J2C, "", "");
	}
	
	//第三方登录游戏
	public void noticeLoginGame(String data)
	{
		JSONObject eventJson = new JSONObject();
		try {
			eventJson.put("account", data);
			eventJson.put("psw", "888888");
			send(Third_NoticeLogin_J2C, "", eventJson.toString());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	//充值 SDK
	private void recharge(String eventParam, JSONObject eventJson)
	{
		try {
			String serverId = eventJson.getString("serverId");
			String loginId = eventJson.getString("loginId");
			String uuid = eventJson.getString("uuid");
			String roleName = eventJson.getString("roleName");
			int roleLv = eventJson.getInt("roleLv");
			String itemId = eventJson.getString("itemId");
			String itemName = eventJson.getString("itemName");
			int itemPrice = eventJson.getInt("itemPrice");
			int itemNum = eventJson.getInt("itemNum");
			String extraMsg = eventJson.getString("extraMsg");
			String paymentType = eventJson.getString("paymentType");
			
			String unionId = PropertiesData.getInstance().getString(ProperTiesCondefine.UNION_ID);
			
			ThirdPay.create().run(serverId,loginId, uuid, roleName, roleLv, 
					itemId, itemName, itemPrice, itemNum, extraMsg, paymentType, unionId);
			
			} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	
	}
	public void sendRechargeResult()
	{
		send(Third_Recharge_J2C, "", "");
	}
	public void setLoginBtnStatus(boolean flag)
	{
		send(Third_OperateLoginBtn_J2C, String.valueOf(flag), "");
	}
	
	//设置登录服地址
	public void sendLoginAddress()
	{
		String ip = PropertiesData.getInstance().getString(ProperTiesCondefine.LOGIN_SERVER_IP);
		String port = PropertiesData.getInstance().getString(ProperTiesCondefine.LOGIN_SERVER_PORT);
		JSONObject eventJson = new JSONObject();
		try {
			eventJson.put("IP", ip);
			eventJson.put("Port", port);
			send(Third_SetLoginServiceAddress_J2C, "", eventJson.toString());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	//发送手机信息
	public void sendPhoneInfo()
	{
		JSONObject eventJson = new JSONObject();
		try {
			eventJson.put("MODEL", SuperTools.getInstance().getModel());	//手机模式
			eventJson.put("IMEI", SuperTools.getInstance().getIMEI());		//手机标识
			String unionId = PropertiesData.getInstance().getString(ProperTiesCondefine.UNION_ID);
			eventJson.put("UnionId", Integer.valueOf(unionId));				//渠道号
			
			String temp_lib = SuperTools.getInstance().readLocalFile(RMConstDefine.KEY_CLIENT_VERSION_LIB);
			String temp_res = SuperTools.getInstance().readLocalFile(RMConstDefine.KEY_CLIENT_VERSION_RES);
			eventJson.put("LibVersion", temp_lib);
			eventJson.put("ResVersion", temp_res);
			
			eventJson.put("APKVersionCode", SuperTools.getInstance().getVersionCode());
			eventJson.put("APKVersionName", SuperTools.getInstance().getVersionName());
			
			eventJson.put("isThirdLogin", ThirdLogin.isThirdLogin);
			eventJson.put("isShowUILoginBtn", false);
//			eventJson.put("isAutoEntryGame", false);
			
			L.d("=====eventJson:" + eventJson.toString());
			send(Third_SavePhoneInfo_J2C, "", eventJson.toString());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void setPlayBgSound(boolean bool) {
		String isPlay = "false";
		if (bool) {
			isPlay = "true";
		}
		else {
			isPlay = "false";
		}
		CPPManager.getInstance().send(Third_Set_BackSound_C2J, isPlay, "");
	}
}
